import { reqCartList, reqDeleteCartById, reqUpdateCheckedById } from "@/api"

const state = {
    cartList: []
}
const actions = {
    async getCartList({ commit }) {
        let result = await reqCartList()
        if (result.code == 200) {
            commit('GETCARTLISI', result.data)
        }
    },
    // 删除购物车某个产品
    async deleteCartById({ commit }, skuId) {
        let result = await reqDeleteCartById(skuId)
        if (result.code == 200) {
            return 'ok'
        }
    },
    // 修改购物车某个产品的选中信息
    async updateCheckedById({ commit }, { skuId, isChecked }) {
        let result = await reqUpdateCheckedById(skuId, isChecked)
        if (result.code == 200) {
            console.log(result)
        }
    },
    // 删除所有商品
    deleteAllCheckedCart({ dispatch, getters }) {
        let promiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            if (item.isChecked == 1) {
                let promise = dispatch('deleteCartById', item.skuId)
                promiseAll.push(promise)
            }
        })
        return Promise.all(promiseAll)
    },
    // 全选修改商品状态
    updateAllCartisChecked({ dispatch, getters }, isChecked) {
        let promiseAll = []
        getters.cartList.cartInfoList.forEach((item) => {
            let promise = dispatch('updateCheckedById', { skuId: item.skuId, isChecked })
            promiseAll.push(promise)
        })
        return Promise.all(promiseAll)
    }
}
const mutations = {
    GETCARTLISI(state, cartList) {
        state.cartList = cartList
    },
    // 修改商品的选中属性
}
const getters = {
    cartList(state) {
        return state.cartList[0] || []
    }
}

export default {
    state,
    actions,
    mutations,
    getters
}